<template>

  <div class="app-container">


    <el-row :gutter="20">
      <!-- 产线选择-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="plId" placeholder="请输入产线" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px" />
        </div>

        <div class="head-container">
          <el-tree :data="plOptions" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode"
            ref="tree" default-expand-all @node-click="handleNodeClick" />
        </div>
      </el-col>
      <!-- 产线配置 -->
      <el-col :span="20" :xs="24">
        <label>{{siteTitle}}</label>
        <el-divider></el-divider>

        <!--        <el-row :gutter="10" class="mb8" v-show="showSitebtn">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['mes:site:add']">新增</el-button>
          </el-col>
        </el-row> -->

        <!-- 产线列表-->
        <!--        <el-table :data="productLlineList" v-show="showProLine">
          <el-table-column label="ID" align="center" prop="id" v-if="false" />
          <el-table-column label="产线编号" align="center" prop="plId" />
          <el-table-column label="产线名称" align="center" prop="plName" />
          <el-table-column label="状态" align="center" prop="status" v-if="false" />
          <el-table-column label="产线图片">
            <template slot-scope="scope">
              <el-image style="width: 100px; height: 80px" :src="scope.row.plImg" :preview-src-list="getImgList(scope.row.plImg)">
                <div slot="error" class="image-slot">
                </div>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remark" v-if="false" />
          <el-table-column label="设置" align="center" class-name="small-padding fixed-width" v-if="false">
          </el-table-column>
        </el-table> -->

        <!-- 工位列表 -->
        <!--        <el-table :data="siteList" v-show="showSite">
          <el-table-column label="顺序" align="center" prop="num" width="50" />
          <el-table-column label="工位编号" align="center" prop="siteId" />
          <el-table-column label="工位名称" align="center" prop="siteName" />
          <el-table-column label="设置" align="center" class-name="small-padding fixed-width">
          </el-table-column>
        </el-table> -->


        <!-- 工位详情 -->
        <el-row :gutter="10" class="mb8" v-show="showInfo">


          <el-col :span="7" :xs="24">
            <el-card class="box-card">

              <el-image :src="proLineImg" :preview-src-list="getImgList(proLineImg)"></el-image>

              <ul class="list-group list-group-striped">
                <li class="list-group-item" v-show="showSiteParam">
                  顺序:<div class="pull-right">{{siteNum}}</div>
                </li>

                <li class="list-group-item">
                  {{preName}}编号:<div class="pull-right">{{proLineId}}</div>
                </li>
                <li class="list-group-item">
                  {{preName}}名称: <div class="pull-right">{{proLineName}}</div>
                </li>
              </ul>
            </el-card>
          </el-col>
          <el-col :span="17" :xs="24">

            <el-card class="box-card" v-show="showSiteParam" style="margin-bottom: 10px;">

              <div slot="header" class="clearfix">
                <span>OPC配置</span>

              </div>
              <div class="text item">
                <el-button type="primary" icon="el-icon-edit-outline" size="mini" style="margin-bottom: 10px;" v-show="showSiteSetEditBtn"
                  @click="editSet">编辑配置</el-button>

                  <el-button type="primary" icon="el-icon-share" size="mini" style="margin-bottom: 10px;" v-show="showSiteSetEditBtn"
                    @click="testCon">测试连接</el-button>

                <el-button type="success" icon="el-icon-check" size="mini" style="margin-bottom: 10px;" v-show="showSiteSetSaveBtn"
                  @click="saveSet">保存配置</el-button>

                <el-form ref="form" :model="form" label-width="80px">

                  <el-form-item label="opc地址">
                    <el-input v-model="form.opcUrl" style="width: 300px;" :disabled="editShow">
                      <template slot="prepend">opc.tcp://</template>
                    </el-input>
                  </el-form-item>

                  <el-form-item label="用户名">
                    <el-input v-model="form.opcName" style="width: 200px;" :disabled="editShow"></el-input>
                  </el-form-item>

                  <el-form-item label="密码">
                    <el-input v-model="form.opcPwd" style="width: 200px;" :disabled="editShow"></el-input>
                  </el-form-item>

                </el-form>
              </div>




            </el-card>

            <el-card class="box-card" v-show="showSite">

              <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" style="margin-bottom: 10px;">新增工位</el-button>

              <el-table :data="siteList" border>
                <el-table-column label="顺序" align="center" prop="num" width="60" />
                <el-table-column label="工位编号" align="center" prop="siteId" width="100" />
                <el-table-column label="工位名称" align="center" prop="siteName" />
                <el-table-column label="OPC地址" align="center" prop="opcUrl" />
                <el-table-column label="工位图片" align="center" width="100">

                  <template slot-scope="scope">

                    <el-image style="width: 40px; height: 50px" :src="scope.row.siteImg" :preview-src-list="getImgList(scope.row.siteImg)">
                      <div slot="error" class="image-slot">

                      </div>
                    </el-image>
                  </template>

                </el-table-column>
                <el-table-column label="设置" align="left">
                  <template slot-scope="scope">
                    <el-button size="mini" :disabled="scope.$index===0" @click="moveUp(scope.$index,scope.row)"><i
                        class="el-icon-arrow-up"></i></el-button>
                    <el-button size="mini" :disabled="scope.$index===(siteList.length-1)" @click="moveDown(scope.$index,scope.row)"><i
                        class="el-icon-arrow-down"></i></el-button>
                    <el-button size="mini" icon="el-icon-delete" type="danger" @click="delSite(scope.row)"></el-button>
                  </template>
                </el-table-column>

                </el-table-column>
              </el-table>





            </el-card>

            <el-card class="box-card" v-show="showSiteParam">

              <div slot="header" class="clearfix">
                <span>动作配置</span>

              </div>
              <div class="text item">
                <el-button type="primary" icon="el-icon-plus" size="mini" style="margin-bottom: 10px;" @click="handelAddAct">新增动作</el-button>

                <el-table :data="siteActList" border>
                  <el-table-column prop="id" label="ID" width="100" v-if="false">
                  </el-table-column>
                  <el-table-column prop="proActId" label="动作编号" width="150">
                  </el-table-column>
                  <el-table-column prop="proActName" label="动作名称">
                  </el-table-column>

                  <el-table-column label="操作" align="left">
                    <template slot-scope="scope">
                      <el-button size="mini" type="success" slot="reference" @click="getParamList(scope.row)">参数</el-button>
                      <el-button size="mini" type="warning" @click="updateActOfSite(scope.row)">编辑</el-button>

                      <el-button style="margin-left: 10px;" size="mini" icon="el-icon-delete" type="danger" @click="delActOfSite(scope.row)"></el-button>
                    </template>
                  </el-table-column>
                </el-table>

              </div>

            </el-card>

          </el-col>

        </el-row>

      </el-col>


    </el-row>


    <!-- 添加或修改工位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-table :data="siteListPage" v-show="showSite">

        <el-table-column label="工位编号" align="center" prop="siteId" width="100" />
        <el-table-column label="工位名称" align="center" prop="siteName" />
        <el-table-column label="工位图片">

          <template slot-scope="scope">

            <el-image style="width: 40px; height: 50px" :src="scope.row.siteImg" :preview-src-list="getImgList(scope.row.siteImg)">
              <div slot="error" class="image-slot">

              </div>
            </el-image>
          </template>

        </el-table-column>
        <el-table-column label="操作" align="left">
          <template slot-scope="scope">
            <el-button size="mini" type="success" icon="el-icon-check" @click="checkSite(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>


      <pagination v-show="siteListPage_total>0" :total="siteListPage_total" :page.sync="siteListPage_queryParams.pageNum"
        :limit.sync="siteListPage_queryParams.pageSize" @pagination="siteListPage_getList" :page-sizes="siteListPage_pageSizes" />


    </el-dialog>

    <!-- 动作模态框-->
    <el-dialog title="添加动作" :visible.sync="openAct" width="500px" :show-close="false" append-to-body>

      <el-form ref="actForm" :model="actForm" label-width="80px" :rules="actFormRules">


        <el-form-item label="动作编号" prop="proActId">
          <el-input v-model="actForm.proActId" :disabled="proActIdDis">
          </el-input>
        </el-form-item>

        <el-form-item label="动作名称" prop="proActName">
          <el-input v-model="actForm.proActName">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitActForm">确 定</el-button>
        <el-button @click="actFormCancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-drawer :title="paramTitle" :visible.sync="drawer_param" :with-header="true">

      <el-table :data="paramList">
        <el-table-column prop="id" label="ID" v-if="false">
        </el-table-column>
        <el-table-column prop="paramId" label="参数编号">

          <template slot-scope="scope">
            <span v-if="scope.row.id!=null">{{scope.row.paramId}}</span>
            <el-input v-else v-model="scope.row.paramId" placeholder="请输入内容"></el-input>

          </template>
        </el-table-column>
        <el-table-column prop="paramName" label="参数名称">

          <template slot-scope="scope">
            <span v-show="scope.row.isEdit==false">{{scope.row.paramName}}</span>
            <el-input v-show="scope.row.isEdit" v-model="scope.row.paramName" placeholder="请输入内容"></el-input>
          </template>

        </el-table-column>
        <el-table-column prop="paramType" label="参数类型" width="110">

          <template slot-scope="scope">
            <!-- old-->
<!--            <span v-show="scope.row.isEdit==false">{{scope.row.paramType}}</span>
            <el-input v-show="scope.row.isEdit" v-model="scope.row.paramType" placeholder="请输入内容"></el-input> -->
            <!-- new -->
             <span v-show="scope.row.isEdit==false">{{scope.row.paramType}}</span>
            <el-select v-show="scope.row.isEdit" v-model="scope.row.paramType" placeholder="请选择类型" clearable size="small">
              <el-option v-for="dict in paramTypeOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="left" width="220">

          <template slot-scope="scope">
            <el-button style="margin-left: 5px;" size="mini" @click="switchEdit(scope.$index,scope.row)" v-show="scope.row.isEdit==false">编辑</el-button>
            <el-button style="margin-left: 5;" size="mini" type="success" v-show="scope.row.isEdit" @click="saveParamEdit(scope.$index,scope.row)">保存</el-button>
            <el-button size="mini" icon="el-icon-delete" type="danger" @click="delParam(scope.$index,scope.row)"></el-button>
          </template>

        </el-table-column>
      </el-table>
      <el-button style="margin-top: 10px; margin-left: 10px;" size="mini" icon="el-icon-plus" type="primary" @click="addParam"></el-button>

    </el-drawer>

  </div>

</template>


<script>
  import {
    listProductLline,
    siteListOfPro,
    getOneSiteOfPro,
    getProductLline,
    updateSiteNumOfPro,
    addSiteForPro,
    delSiteForPro,
    saveSiteSetForPro,
    siteActList,
    getActOne,
    addAct,
    delAct,
    upAct,
    siteParamList,
    addParamForSite,
    editParamForSite,
    delParamForSite,
    getOpc,
    treeselect
  } from "@/api/mes/productLline";
  import {
    listSite
  } from "@/api/mes/site";
  export default {
    name: "Set",
    data() {
      return {

        //产线列表
        showProLine: true,
        productLlineList: undefined,
        proLineImg: undefined,
        proLineId: undefined,
        proLineName: undefined,

        preName: undefined,
        //工位列表
        siteTitle: undefined,
        showSite: false,
        showSitebtn: false,
        siteList: undefined,
        siteNum: undefined,
        //工位详情

        showInfo: false,
        showSiteParam: false,

        //工位选择列表
        siteListPage: undefined,
        form: {
          opcUrl: '',
          opcName: '',
          opcPwd: ''
        },

        editShow: true,
        showSiteSetEditBtn: false,
        showSiteSetSaveBtn: false,
        prolSiteId: undefined,

        // 查询参数
        paramTypeOptions:[],//参数类型 数据字典
        queryParams: {
          plId: null
        },
        siteListPage_queryParams: {
          pageNum: 1,
          pageSize: 5,
          siteName: null,
          plId: null,
          sitePlc: null,
          status: null,
          siteIp: null,
          siteImg: null,
        },
        siteListPage_total: 0,
        siteListPage_pageSizes: [5],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        plId: undefined,
        plOptions: undefined,
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        //
        siteActList: undefined,
        openAct: false,
        proActIdDis: false,
        actForm: {
          id: null,
          proActId: undefined,
          proActName: undefined
        },
        actFormRules: {
          proActId: [{
            required: true,
            message: "编号不能为空",
            trigger: "blur"
          }]
        },

        paramList: undefined,
        showParamPo: false,
        drawer_param: false,
        paramEditShow: 0,
        paramTitle: "",
        drawer_proActId: undefined,

      };
    },
    created() {
      this.getTreeselect()
      this.getProLineList()

      this.getDicts("param_type").then(response => {
        this.paramTypeOptions = response.data;
      });

    },
    methods: {


      siteListPage_getList() {
        listSite(this.siteListPage_queryParams).then(response => {
          this.siteListPage = response.rows;
          this.siteListPage_total = response.total;
          //this.loading = false;
        });
      },
      getProLineList() {
        listProductLline(this.queryParams).then(response => {
          this.productLlineList = response.rows;

        });

      },
      getImgList(img) {
        let images = new Array();
        images.push(img);
        return images;

      },
      getSiteList(data) {

        this.siteTitle = data.label;
        this.showInfo = true;
        this.showSite = true;
        this.showSiteParam = false;
        this.showSiteSetEditBtn = false;
        this.showSiteSetSaveBtn = false;
        this.editShow = true;
        this.queryParams.plId = data.id

        this.preName = "产线";
        //查询产线详情
        listProductLline(this.queryParams).then(response => {
          //console.log(response.rows[0])
          this.proLineImg = response.rows[0].plImg;
          this.proLineId = response.rows[0].plId;
          this.proLineName = response.rows[0].plName;
        });
        //查询产线中的工位
        siteListOfPro(this.queryParams).then(response => {
          this.siteList = response.rows;

        });

      },

      getOneSite(data) {
        this.preName = "工位";
        this.showInfo = true;
        this.showSite = false;
        this.showSiteParam = true;
        this.showSiteSetEditBtn = true;


        getOneSiteOfPro(data.id).then(response => {
          this.proLineImg = response.data.siteImg;
          this.proLineId = response.data.siteId;
          this.proLineName = response.data.siteName;
          this.siteNum = response.data.num;
          this.siteTitle = response.data.plId + "-" + response.data.plName + " > " + response.data.siteName;
          this.prolSiteId = response.data.id;
          this.form.opcUrl = response.data.opcUrl;
          this.form.opcName = response.data.opcName;
          this.form.opcPwd = response.data.opcPwd;
          this.getSiteActList();
        });

      },

      /** 树形菜单点击按钮 */
      handleNodeClick(data) {

        // console.log(data);
        //找父节点 没有父节点说明是产线
        // console.log(this.$refs.tree.getHalfCheckedKeys())
        switch (data.lv) {
          case "1":

            //  console.log("选择了产线")
            this.getSiteList(data);
            break;
          case "2":

            //   console.log("选择了工位")

            this.getOneSite(data);

            break;
          default:
            break;
        }



      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      getTreeselect() {
        console.log("加载树结构")


        treeselect().then(response => {
          this.plOptions = response.data;
        });
      },
      /** 新增按钮操作 */
      handleAdd() {

        this.open = true;
        this.title = "选择工位";
        // 查询条件清空
        this.siteListPage_getList();


      },
      moveUp(index, row) {
        var that = this;
        //   console.log('上移', index, row);
        //  console.log(that.siteList[index]);
        if (index > 0) {
          let upDate = that.siteList[index - 1];
          that.siteList.splice(index - 1, 1);
          that.siteList.splice(index, 0, upDate);
        } else {
          alert('已经是第一条，不可上移');
        }
        this.updateNum();
      },
      //向下移动
      moveDown(index, row) {
        var that = this;
        //  console.log('下移', index, row);
        if ((index + 1) === that.siteList.length) {
          alert('已经是最后一条，不可下移');
        } else {
          //  console.log(index);
          let downDate = that.siteList[index + 1];
          that.siteList.splice(index + 1, 1);
          that.siteList.splice(index, 0, downDate);
        }
        this.updateNum();

      },
      updateNum() {
        //更新工位顺序
        this.siteList.forEach(function(value, index, array) {
          // console.log(value)
          value.num = index + 1;

          updateSiteNumOfPro(value.id, value.num);
        })
        this.getTreeselect();
        //更新后台


      },

      checkSite(row) {
        this.open = false;
        var that = this;
        // console.log(row)
        let siteAdd = {
          "plId": this.proLineId,
          "siteId": row.siteId,
          "num": this.siteList.length + 1
        };
        addSiteForPro(siteAdd).then(response => {
          siteListOfPro(that.queryParams).then(response => {
            that.siteList = response.rows;
            that.getTreeselect()
          });
        })
        // alert();

      },
      delSite(row) {
        var that = this;
        delSiteForPro(row.id).then(response => {
          siteListOfPro(that.queryParams).then(response => {
            that.siteList = response.rows;
            that.getTreeselect()
          });

        });
      },

      editSet() {

        this.editShow = false;
        this.showSiteSetEditBtn = false;
        this.showSiteSetSaveBtn = true;

      },
      saveSet() {
        let data = {
          "prolSiteId": this.prolSiteId,
          "opcUrl": this.form.opcUrl,
          "opcName": this.form.opcName,
          "opcPwd": this.form.opcPwd
        };
        saveSiteSetForPro(data).then(res => {
          this.editShow = true;

          this.showSiteSetEditBtn = true;
          this.showSiteSetSaveBtn = false;
          this.$message({
            message: '保存设置成功',
            type: 'success'
          });
        })


      },

      getSiteActList() {
        let query = {
          "prolSiteId": this.prolSiteId
        }
        siteActList(query).then(res => {

          this.siteActList = res.rows;

        })
      },

      //动作操作
      handelAddAct() {
        this.proActIdDis = false
        this.openAct = true

      },
      //动作表单重置
      actFormReset() {
        this.actForm = {
          id: null,
          proActId: null,
          proActName: null
        }
        this.resetForm("actForm");
      },
      actFormCancel() {
        this.openAct = false
        this.actFormReset()
      },
      submitActForm() {

        this.actForm.prolSiteId = this.prolSiteId;
        this.$refs["actForm"].validate(valid => {

          if (valid) {

            console.log(this.actForm.id)

            if (this.actForm.id == null) {
              addAct(this.actForm).then(res => {
                this.msgSuccess("新增成功");
                this.openAct = false
                this.actFormReset()

                this.getSiteActList();

              })

            } else {


              upAct(this.actForm).then(res => {

                this.msgSuccess("修改成功");
                this.openAct = false
                this.actFormReset()

                this.getSiteActList();
              })

            }


          }

        })

      },
      delActOfSite(row) {
        delAct(row.id).then(res => {
          this.getSiteActList();
        })

      },
      //修改动作
      updateActOfSite(row) {

        getActOne(row.id).then(res => {
          this.openAct = true
          this.proActIdDis = true
          this.actForm.id = res.data.id
          this.actForm.proActId = res.data.proActId
          this.actForm.proActName = res.data.proActName
        })



      },
      getParamList(row) {

        this.drawer_param = true;
        let query = {
          "proActId": row.proActId
        }
        this.drawer_proActId = row.proActId;
        this.paramTitle = row.proActId + "-" + row.proActName + "  参数设置";
        this.showParamPo = true;
        siteParamList(query).then(res => {
          this.paramList = res.rows;

          for (let i = 0; i < this.paramList.length; i++) {
            this.paramList[i].isEdit = false;

          }
        })

      },
      addParam() {

        //还有没 保存的禁止添加
        for (let i = 0; i < this.paramList.length; i++) {

          if (this.paramList[i].isEdit == true) {

            return;
          }

        }

        let newLine = {
          "id": null,
          "paramId": "",
          "paramName": "",
          "paramType": "",
          "isEdit": true,
          "proActId": this.drawer_proActId
        }
        this.paramList.push(newLine);

      },
      switchEdit(index, row) {
        // console.log(row)

        this.paramList[index].isEdit = true
        this.paramList.splice(1, 0)
        //this.paramEditShow=1
      },

      saveParamEdit(index, row) {

        if (row.paramId != null && row.paramId.trim() != "") {

          if (row.id == null) {

            //   this.paramList[index].proActId =?
            addParamForSite(row).then(res => {
              this.msgSuccess("新增成功");
              // this.paramList[index].isEdit = false
              //this.paramList.splice(1, 0)
              let query = {
                "proActId": this.drawer_proActId
              }
              siteParamList(query).then(res => {
                this.paramList = res.rows;

                for (let i = 0; i < this.paramList.length; i++) {
                  this.paramList[i].isEdit = false;

                }
              })
            })

          } else {

            editParamForSite(row).then(res => {

              this.msgSuccess("保存成功");
              let query = {
                "proActId": this.drawer_proActId
              }
              siteParamList(query).then(res => {
                this.paramList = res.rows;

                for (let i = 0; i < this.paramList.length; i++) {
                  this.paramList[i].isEdit = false;

                }
              })
              //   this.paramList[index].isEdit = false
              //this.paramList.splice(1, 0)
            })
          }
        }





      },
      delParam(index, row) {

        if (row.id == null) {

          this.paramList.splice(index, 1)

        } else {
          delParamForSite(row.id).then(res => {
            // this.paramList[index].

           let query = {
             "proActId": this.drawer_proActId
           }
           siteParamList(query).then(res => {
             this.paramList = res.rows;

             for (let i = 0; i < this.paramList.length; i++) {
               this.paramList[i].isEdit = false;

             }
           })
          })
        }

      },
      testCon(){
        let query={
          "opcUrl":this.form.opcUrl,
          "opcName":this.form.opcName,
          "opcPwd":this.form.opcPwd,
        }

        getOpc(query).then(res => {
          console.log(res)
            if(res.code==200){
              this.msgSuccess(res.msg);
            }else{
              this.msgError(res.msg);
            }
        });

      }
    }
  };
</script>
